
/*****  manager ******/

var TopNavBar = React.createClass({
    render: function(){
        var partnerBtns=[];
        var staffBtns=[];
        var customerBtns=[];
        var flag=$.cookie("flag")||"";
        if(flag.indexOf("p")>=0){
            partnerBtns.push(<li><a onClick={function(){toPage('ProductPostPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">发布活动</a></li>);
            partnerBtns.push(<li><a onClick={function(){toPage('ProductPage4Partner',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">活动管理</a></li>);
            partnerBtns.push(<li><a onClick={function(){toPage('FlowMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">账户流水</a></li>);
            partnerBtns.push(<li><a onClick={function(){toPage('PromotionMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">优惠活动</a></li>);
        }
        if(flag.indexOf("a")>=0){
            staffBtns.push(<li><a onClick={function(){toPage('PartnerApplicationMngPage')}.bind(this)} href="javascript:;">合作申请</a></li>);
            staffBtns.push(<li><a onClick={function(){toPage('PartnerMngPage')}.bind(this)} href="javascript:;">合作方管理</a></li>);
            staffBtns.push(<li><a onClick={function(){toPage('PrimaryAccountMngPage')}.bind(this)} href="javascript:;">主账户流水</a></li>);
            staffBtns.push(<li><a onClick={function(){toPage('InvoiceMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">应付账款</a></li>);
            staffBtns.push(<li><a onClick={function(){toPage('AdvertisementMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">广告管理</a></li>);
        }
        return (
<nav className="navbar navbar-inverse navbar-static-top">
    
        <div className="navbar-header">
            <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">菜单</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <h3>管理  <a className="" href="/index.html"><small className="userinfo">退出</small></a></h3>

        </div>
        <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul className="nav navbar-nav mm">
                {customerBtns}
                {partnerBtns}
                {staffBtns}
            </ul>
            <ul className="nav navbar-nav navbar-right">
                <li></li>
                <li className="dropdown">
                </li>
            </ul>
        </div>
</nav>)
    }
});

var SideNavBar = React.createClass({
    render: function(){
        var partnerBtns=[];
        var staffBtns=[];
        var customerBtns=[];
        var flag=$.cookie("flag")||"";
        if(flag.indexOf("p")>=0){
            partnerBtns.push(<li><a onClick={function(){toPage('ProductPostPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">发布活动</a></li>);
            partnerBtns.push(<li><a onClick={function(){toPage('ProductPage4Partner',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">活动管理</a></li>);
            partnerBtns.push(<li><a onClick={function(){toPage('FlowMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">账户流水</a></li>);
            partnerBtns.push(<li><a onClick={function(){toPage('PromotionMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">优惠活动</a></li>);
        }
        if(flag.indexOf("a")>=0){
            staffBtns.push(<li><a onClick={function(){toPage('PartnerApplicationMngPage')}.bind(this)} href="javascript:;">合作申请</a></li>);
            staffBtns.push(<li><a onClick={function(){toPage('InvoiceMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">应付账款</a></li>);
            
        }
        return (
          <div id="sidebar-wrapper">
                   
                   
               </div>
      )
    }
});

/****** manage pages *********/



var ShopList4Partner = React.createClass({
    handleOpenModal: function(){
        $('#shopModal').modal('show');
    },
    render: function() {
        var shopOptions=this.props.shops.map(function(shop){
            return (<option value={shop.id}>{shop.name}</option>);
        });

        return (
            <div className="input-group">
               <span className="input-group-addon">场地：</span>
               <select name="shop_id" className="form-control">
                {shopOptions}
               </select>
               <span className="input-group-btn"><a onClick={this.handleOpenModal} className="btn btn-primary" type="button"> 新增场地 </a></span>
            </div>
         );
    }
});


$.extend(ProductGrid.prototype,{
    handleProductClick: function(product){
        toPage('OrderList4Porduct',{product:product,partnerId:this.props.partnerId,productId:product.id});
    },
    render: function(){
        var self=this;
        var items = this.props.products.map(function(product){
            var startTime=new Date(product.startTime).Format('MM-dd hh:mm')+' - '+new Date(product.endTime).Format('hh:mm');
            return (<div>
            <div className="col-xs-8" style={{borderTop:'1px solid #eee',padding:'4px 0'}}>
                <a className="block" href="javascript:;" onClick={self.handleProductClick.bind(self,product)}>
                    <div className="col-xs-6">{product.name}</div><div className="col-xs-6">  {product.shopName}</div>
                    <div className="col-xs-12"><small>{startTime}</small></div>
                </a>
            </div>
            <div className="col-xs-4 btn-group">
                <button className="btn btn-warning" onClick={this.handleProductInactive.bind(this,product)}><span className="glyphicon glyphicon-remove"/></button>
                <button onClick={function(){toPage('ProductPostPage',{partnerId:partnerId,product:product},'#/product/edit?'+product.id)}} className="btn btn-primary"><span className="glyphicon glyphicon-edit"/></button>
            </div>
            </div>);
        }.bind(this))

        return (<div>
            <div className="clear-both">
                {items}
             </div>
        </div>);
    }
})

var ProductPage4Partner = React.createClass({
    loadData:function(){
      $.get('/api/partners/'+this.props.partnerId+'/products?page=0',function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render: function(){
        return (<div>
            <SubMenuBar brand="活动列表"><li><a className="btn btn-default" onClick={function(){toPage('ProductPostPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">发布活动</a></li></SubMenuBar>
            <GridHeader collection={this.state.collection} handleRefresh={this.loadData.bind(this)} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,-1)}/>
            <ProductGrid products={this.state.content} partnerId={this.props.partnerId} />
        </div>);
    }
});

$.extend(ProductPage4Partner.prototype,GridPageMixin);

var OrderList4Porduct = React.createClass({
    scanCode:function(){
        API.wxScanQRCode(function(res){
            $.get('/api/partners/'+this.props.partnerId+'/products/'+this.props.productId+'/orders?page=0&uid='+res,function(data){
                console.log(data);
                if(data.content.length>0){
                    var order=data.content[0];
                    toPage('OrderConfirmPage',{order:order,amount:order.amount,partnerId:this.props.partnerId},'#/order/confirm?id='+order.id);
                }
            }.bind(this))
        }.bind(this))
    },
    getInitialState: function() {
            return {orders:[]};
    },
    componentDidMount: function(){
        $.get('/api/partners/'+this.props.partnerId+'/products/'+this.props.productId+'/orders?page=0',function(data){
            //console.log(data);
            this.setState({orders:data.content});
        }.bind(this));
    },
    render: function(){
        var product=this.props.product||{};
        var items = this.state.orders.map(function(order){
            return (<OrderRow4Product order={order} {...this.props}/>);
        }.bind(this))
        return (<div>
            <SubMenuBar brand="活动确认"><li> <a  onClick={this.scanCode} href="javascript:;">扫码确认</a></li></SubMenuBar>
            <ProductRow product={product} />

            <ul className="list-group clear-both">
                {items}
             </ul>

        </div>);
    }
});

var OrderConfirmPage= React.createClass({
    handleConfirmOrder: function(male,female,absence){
        console.log(male,female,absence);
        $.post('/api/partners/'+this.props.partnerId+'/orders/'+this.props.order.orderId+"/confirm",{full:male,feature:female,returned:absence},function(order){
            if(this.props.onConfirmed){
                this.props.onConfirmed(order)
            }else{
                history.back();
            }
        }.bind(this));
    },
    handleMaleChange: function(v){
        if(v+this.state.female<=this.props.amount){
            this.setState({male:v});
            return false;
        }
        return true;
    },
    handleFemaleChange: function(v){
        if(v+this.state.male<=this.props.amount){
            this.state.female=v;
            this.setState(this.state);
            return false;
        }
        return true;
    },
    getInitialState: function() {
            return {male:this.props.amount||0,female:0};
    },
    render:function(){
        var order=this.props.order||{}
        var male=this.state.male;
        var female=this.state.female||0;
        var absence=this.props.amount-male-female;
        return (
            <div>
                <div className="col-xs-4">名称:</div><div className="col-xs-8">{order.productName}</div>
                <div className="col-xs-4">金额:</div><div className="col-xs-8">¥ {order.total} </div>
                
                <div className="col-xs-4">实到人数:</div><div className="col-xs-8"><NumberSelector name="numMale" value={male} onChange={this.handleMaleChange} /></div>
                <div className="col-xs-4">缺席人数:</div><div className="col-xs-8">{absence}</div>
                 <div className="input-group">
                      <span id="note"></span>
                  </div>

                 <div className="input-group">
                 <span className="input-group-btn">
                     <button className="btn btn-success" onClick={this.handleConfirmOrder.bind(this,male,female,absence)}>确认</button>
                   </span>
                 </div>
            </div>);
    }
})

var OrderRow4Product = React.createClass({
    onConfirmed:function(order){
        $('#confirmModal',this.getDOMNode()).modal('hide');
        this.setState({status:order.statusText})
    },
    openConfirmOrder:function(){
        $('#confirmModal',this.getDOMNode()).modal('show');
    },
    getInitialState: function() {
            return {customer:{},status:this.props.order.orderStatus};
    },
    componentDidMount: function() {
        var order=this.props.order;
        var productId=order.productId;
        var self=this;
        $.get('/api/public/customers/'+order.customerId,function(data){
            self.setState({customer:data,status:order.orderStatus});
        })
    },
    render: function(){
        var order=this.props.order||{};
        var status = this.state.status;
        var customer=this.state.customer||{}
        var time=new Date(order.createTime).Format('yyyy-MM-dd')
        if(status=="已支付"){
            status= <button onClick={this.openConfirmOrder} className="btn btn-success">确认</button>;
        }
        return (<div className="panel panel-success">
                    <div className="panel-body">
                    <table>
                    <tr><td rowSpan="2"><UserBadge customer={this.state.customer} /></td><td colSpan="2">报名时间： <small>{time}</small></td></tr>
                    <tr><td>{status}</td><td><span>{order.note}</span>  报名人数：{order.amount}</td></tr>
                    </table>
                    <Modal id="confirmModal"><OrderConfirmPage {...this.props} onConfirmed={this.onConfirmed} order={order} amount={order.amount} male={0} female={0}/></Modal>
                    </div>
                </div>);
    }
});

$.extend(ProductPostPage.prototype,{
    done: function(){
        toPage('ProductPage4Partner',{partnerId:partnerId}); 
    },
    render: function() {
            
            var customer=this.props.customer||{};
            var product=this.props.product||{};
            var metaData=product.metaData||{};
            var parter = this.state.parter||{};
            var picture=this.state.picture;
            return (
            <div className="clear-both">
                <SubMenuBar brand="发布活动" withback="true"><li><a onClick={this.handleSubmitProduct} href="javascript:;">保存</a></li></SubMenuBar>
                <form className="ProductForm" method="post">
                    <input type="hidden" name="_id" value={product.id||this.props.productId} />
                    <input type="hidden" name="partner_id" value={this.props.partnerId} />
                    <input type="hidden" name="limited" value={1} />
                    <input type="hidden" id="picture_id" name="picture_id" value={this.state.picture} />
                    <ShopList4Partner partnerId={this.props.partnerId} shops={this.state.shops} selected={product.shopId}/>
                    <div className="input-group">
                      <span className="input-group-addon">标题：</span>
                      <input name="_name" defaultValue={product.name} type="text" className="form-control" data-rule-required="true"  data-msg-required="此项不能为空！"/>
                    </div>
                    <div className="input-group">
                      <span className="input-group-addon">类型：</span>
                      <select name="cat1_name" defaultValue={product.cat1} className="form-control">
                          <option value="羽毛球">羽毛球</option>
                          <option value="篮球">篮球</option>
                          <option value="足球">足球</option>
                      </select>
                    </div>
                    <div className="input-group">
                      <span className="input-group-addon">活动时段：</span>
                      <LinkedDatePicker nameStart="_startDate" nameEnd="_endDate" start={product.startTime} end={product.endTime} />
                    </div>
                    <div className="input-group">
                      <span className="input-group-addon">报名取消截止时间：</span>
                      <select name="dueBeforeStart" defaultValue={"3"} className="form-control">
                          <option value="1">开始前1小时</option>
                          <option value="2">开始前2小时</option>
                          <option value="3">开始前3小时</option>
                          <option value="4">开始前4小时</option>
                          <option value="5">开始前5小时</option>
                          <option value="6">开始前6小时</option>
                          <option value="24">开始前1天</option>
                          <option value="48">开始前2天</option>
                          <option value="72">开始前3天</option>
                      </select>
                    </div>
                    
                    <div className="input-group">
                      <span className="input-group-addon">人均费用：</span>
                      <input name="_price" defaultValue={product.price} type="number" className="form-control" data-rule-required="true" data-rule-number="true" data-rule-min="0" data-msg-min="妈呀，小学没毕业不认识负数！" data-msg-required="此项不能为空！" data-msg-number="请输入数字"/>
                      <span className="input-group-addon">.00元</span>
                    </div>
                    
                    <div className="input-group">
                      <span className="input-group-addon">组织者：</span>
                      <input name="creator" defaultValue={metaData.creator} type="text" className="form-control" data-rule-required="true"  data-msg-required="此项不能为空！"/>
                    </div>
                    <div className="input-group">
                      <span className="input-group-addon">联系电话：</span>
                      <input name="phone" defaultValue={metaData.phone}  type="text" className="form-control"  data-rule-required="true"  data-msg-required="此项不能为空！"/>
                    </div>

                    <div className="input-group">
                      <span className="input-group-addon">备注：</span>
                      <input name="_remark" defaultValue={product.remark} type="text" className="form-control"/>
                    </div>
                    <div className="input-group">
                      <span className="input-group-addon">人数上限：</span>
                      <input name="_quantity" defaultValue={product.quantity} type="number" className="form-control" data-rule-required="true" data-rule-number="true" data-rule-min="0" data-msg-min="妈呀，小学没毕业不认识负数！" data-msg-required="此项不能为空！" data-msg-number="请输入数字"/>
                    </div>
                    <div className="input-group">
                      <input name="no_promotion" defaultChecked={product.disablePromotion} type="checkbox" />
                      <span >不参加促销活动</span>
                    </div>
                    <FileUploader picture={picture} onUploaded={this.onUploaded}/>

                    <div className="input-group  col-xs-12 col-md-3">
                        <button onClick={this.handleSubmitProduct} type="button" className="btn btn-primary">保存</button>
                    </div>
                </form>
                <Modal id="shopModal">
                    <ShopPage partnerId={this.props.partnerId} onChange={function(){this.loadShops();}.bind(this)}/>
                </Modal>
             </div>
            );
        }
});


